package v2.chapter2.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipTest1 {

	public static void main(String[] args) throws IOException {
		File fileSrc = new File("F:\\logs");
		File destFile = new File("F:\\logs.zip");
		zip(fileSrc, destFile);
		
		File zipFile = new File("F:\\logs.zip");
		String destDir = "F:\\logs\\";
		unzip(zipFile, destDir);
	}
 

	public static void zip(File fileSrc, File dectFile) throws IOException {
		ZipOutputStream zipOutputStream = new ZipOutputStream(
				new CheckedOutputStream(new FileOutputStream(dectFile), new CRC32()));
		String name = fileSrc.getName();
		zip(zipOutputStream, name, fileSrc);
		zipOutputStream.flush();
		zipOutputStream.close();
	}

	private static void zip(ZipOutputStream zipOutputStream, String name, File fileSrc) throws IOException {
		if (fileSrc.isDirectory()) {
			File[] files = fileSrc.listFiles(new FilenameFilter() { // 过滤文件
				Pattern pattern = Pattern.compile(".+");// 所有文件，正则表达式

				@Override
				public boolean accept(File dir, String name) {
					return pattern.matcher(name).matches();
				}
			});
			zipOutputStream.putNextEntry(new ZipEntry(name + "/")); // 建一个文件夹
			name = name + "/";
			for (File f : files) {
				zip(zipOutputStream, name + f.getName(), f);
			}
		} else {
			zipOutputStream.putNextEntry(new ZipEntry(name));
			FileInputStream input = new FileInputStream(fileSrc);
			byte[] buf = new byte[1024];
			int len = -1;
			while ((len = input.read(buf)) != -1) {
				zipOutputStream.write(buf, 0, len);
			}
			zipOutputStream.flush();
			input.close();
		}
	}

	private static void unzip(File zipFile, String destDir) throws IOException {
		ZipInputStream zipInputStream = new ZipInputStream(
				new CheckedInputStream(new FileInputStream(zipFile), new CRC32()));
		ZipEntry zipEntry;
		while ((zipEntry = zipInputStream.getNextEntry()) != null) { 
			File f = new File(destDir + zipEntry.getName());
			if (zipEntry.getName().endsWith("/")) {
				f.mkdirs();
			} else {
				FileOutputStream fileOutputStream = new FileOutputStream(f);
				byte[] buf = new byte[1024];
				int len = -1;
				while ((len = zipInputStream.read(buf)) != -1) {
					fileOutputStream.write(buf, 0, len);
				}
				fileOutputStream.flush();
				fileOutputStream.close();
			}
			// 关闭该条目
			zipInputStream.closeEntry(); 
		}
		zipInputStream.close();
	}
}
